package com.example.waimai.controller;

import com.example.waimai.pojo.User;
import com.example.waimai.serviceImp.UserLoginServiceImp;
import com.example.waimai.util.JwtUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
public class UserLoginController {

    @Autowired
    private UserLoginServiceImp userLoginServiceImp;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostMapping("UserLogin")
    public Map<String,String> userLogin(@RequestBody User user){
        HashMap<String,String> result = new HashMap<>();
        String telephone = user.getTelephone();
        String password = user.getPassword();
        if(password == null || telephone == null){
            result.put("error","用户名或者密码未输入");
        }else{
             user = userLoginServiceImp.userLogin(telephone,password);
            if(user!=null){
                //登录成功 ，生成tokenId
                String tokenId = JwtUtil.generate(telephone);
                result.put("tokenId",tokenId);
                result.put("UserId", String.valueOf(user.getId()));
                result.put("userEmail",user.getEmail());
                result.put("userName",user.getUserName());
                result.put("userImage",user.getUserImage());
            }else{
                // 操作失败了
                result.put("error","操作失败");
            }
        }
        return result;
    }

    /*注册成功之后，直接进入主页面*/
    @PostMapping("UserRegister")
    public User userRegister(@RequestBody User user){
        return userLoginServiceImp.register(user);
    }

    /*验证一下验证码*/
    @PostMapping("userVerifyCode")
    public Boolean userVerifyCode(@RequestBody Map<String,String> param){
        return userLoginServiceImp.verifyCode(param.get("email"),param.get("code"));
    }

    // 预处理用户信息
    @PostMapping("getUserId")
    public User getUserId(@RequestBody User param){

        return  userLoginServiceImp.getUserIdByTelephone(param.getTelephone(),param.getPassword());
    }

    // 获取验证码
    @PostMapping("getVerifyCode")
    public Boolean getVerifyCode(@RequestBody String email){
        // 发送一条消息到 消息队列即可
        email = email.substring(1,email.length()-1);
        rabbitTemplate.convertAndSend("verify",email);
        return true;
    }


}
